package com.itboye.jigongbao.activity

import android.Manifest
import android.content.Intent
import android.os.Build
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.TextView
import com.itboye.jigongbao.MainActivity
import com.itboye.jigongbao.R
import com.itboye.jigongbao.app.MyApplication
import com.itboye.jigongbao.base.BaseActivity
import com.itboye.jigongbao.bean.LoginInfo
import com.itboye.jigongbao.logincontroller.LoginController
import com.itboye.jigongbao.logincontroller.LoginedState
import com.itboye.jigongbao.retrofit.base.ResultEntity
import com.itboye.jigongbao.retrofit.presenter.UserPrestener
import com.itboye.jigongbao.utils.*
import com.itboye.jigongbao.utils.ToastUtil.ByAlert
import com.itboye.jigongbao.utils.permission.PermissionListener
import kotlinx.android.synthetic.main.activity_login.*
import java.util.*


class LoginActivity : BaseActivity(), Observer {
    override fun update(p0: Observable?, p1: Any?) {
        var entity = p1 as ResultEntity
        when (entity.eventType) {
            UserPrestener.By_SecurityCode_send_Success -> {
                ByAlert.alert(entity.data)
                timeCount!!.start()
            }
            UserPrestener.By_SecurityCode_send_Fail -> {
                ByAlert.alert(entity.msg)
            }
            UserPrestener.By_UserAccount_loginByMobile_Success -> {
                MyApplication.instance!!.mACache!!.put(Const.LOGIN_INFO, entity.data as LoginInfo)
                SPUtils.put(this, null, Const.ROLE, (if (identityType.equals("14")) {
                    Const.WORKER
                } else {
                    Const.FORCEMAN
                }))
                SPUtils.put(this, null, Const.HAS_LOGIN, true)
                MyApplication.instance!!.loginInfo = entity.data as LoginInfo
                LoginController.setLoginState(LoginedState())
                mIntent = Intent(LoginActivity@ this, MainActivity::class.java)
                startActivity(mIntent)
                finish()
                ByAlert.alert("登录成功")
            }
            UserPrestener.By_UserAccount_loginByMobile_Fail -> {
                ByAlert.alert(entity.msg)
            }
            else -> {
                ByAlert.alert(entity.msg)
            }
        }
    }


    var btn_login_by_worker: Button? = null
    var txt_send_code: TextView? = null
    var radio_gongren: TextView? = null
    var radio_gongtou: TextView? = null
    var txt_login_by_forceman: TextView? = null
    var userPresenter: UserPrestener? = null
    var PERMISSIONS: Array<String> = arrayOf(Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_CONTACTS)
    var timeCount: TimeCount? = null
    override fun getLayoutId(): Int {
        return R.layout.activity_login
    }

    override fun initData() {
        TitleBarUtils().initTitlebarStyle1(this, this!!.trans_action_login!!, "登录", 0, "", 0, "")
        radio_gongren!!.isSelected = true
        timeCount = TimeCount(60000, 1000, txt_send_code)
        userPresenter = UserPrestener(this)
        setSelectIdentity(radio_gongren)
    }

    private var mobile: String? = null

    private var code: String? = null

    private var mIntent: Intent? = null

    override fun onClick(p0: View?) {
        Log.v(Const.TAG_DEBUG, "" + SPUtils.getSp(Const.ROLE))
        when (p0) {
            btn_login_by_worker -> {
                requestRunPermission(true)
            }
            txt_login_by_forceman -> {
                requestRunPermission(false)
            }
            radio_gongren -> {
                setSelectIdentity(radio_gongren)
            }
            radio_gongtou -> {
                setSelectIdentity(radio_gongtou)
            }
            txt_send_code -> {
                mobile = edit_login_mobile.text.toString()
                if (mobile.equals("")) {
                    ByAlert.alert("手机号码为空")
                    return
                }
                if (mobile!!.length < 11) {
                    ByAlert.alert("手机号码有误")
                    return
                }
                userPresenter!!.By_SecurityCode_send("+86", mobile, 5, "sms_juhe", 120, this)
            }
            else -> {
            }
        }
    }

    private fun requestRunPermission(identity: Boolean) {
        // 缺少权限时, 进入权限配置页面
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestRunPermisssion(PERMISSIONS, object : PermissionListener {
                override fun onGranted() {
                    //表示所有权限都授权了
//                    ByAlert.alert("所有权限都授权了，可以搞事情了")
                    //我们可以执行打电话的逻辑
                    onLogin(identity)
                }

                override fun onDenied(deniedPermission: List<String>) {
//                    for (permission in deniedPermission) {
//                        ByAlert.alert("被拒绝的权限：" + permission)
//                    }
//                    ByAlert.alert("被拒绝的权限：" + deniedPermission.toString())
                    if (deniedPermission!!.size > 0) {
                        showPermission(this@LoginActivity)
                    }
                }
            })
        } else {
            onLogin(identity)
        }
    }

    private var identityType: String? = null

    private fun onLogin(identity: Boolean) {
        identityType = ""
        mobile = edit_login_mobile.text.toString()
        if (mobile.equals("")) {
            ByAlert.alert("手机号码为空")
            return
        }
        code = edit_login_code.text.toString()
        if (code.equals("")) {
            ByAlert.alert("验证码为空")
            return
        }
        /**
         * identity true: 普通工人 false:工头
         * 普通工人=14,工头=13
         **/
        if (identity) {
            identityType = "14"
        } else {
            identityType = "13"
        }
        userPresenter!!.By_UserAccount_loginByMobile("+86", mobile, code!!, null, identityType, MobileUtil.Companion.getDeviceToken(), "android", this)
    }


    private fun setSelectIdentity(radio: TextView?) {
        radio_gongtou!!.setBackgroundDrawable(resources.getDrawable(R.drawable.radio_bg_white_rounded_border_gray))
        radio_gongren!!.setBackgroundDrawable(resources.getDrawable(R.drawable.radio_bg_white_rounded_border_gray))
        radio_gongtou!!.setTextColor(resources.getColor(R.color.black))
        radio_gongren!!.setTextColor(resources.getColor(R.color.black))
//        if (radio!!.isSelected) {
        radio!!.setBackgroundDrawable(resources.getDrawable(R.drawable.radio_bg_white_rounded_border_green))
        radio!!.setTextColor(resources.getColor(R.color.white))
//        } else {
//            radio.setBackgroundDrawable(resources.getDrawable(R.drawable.radio_bg_white_rounded_border_gray))
//        }
        radio!!.isSelected = !radio!!.isSelected
    }

}
